package com.kimho.cuttrucker.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.kimho.core.PageInfo;
import com.kimho.cuttrucker.domain.CutTrucker;
import com.kimho.cuttrucker.persistence.CutTruckerMapper;
import com.kimho.product.persistence.ProductMapper;
import com.kimho.util.Util;

@Service
public class CutTruckerService {
	@Autowired
	private CutTruckerMapper cutTruckerMapper;
	
	@Autowired
	private ProductMapper productMapper;
	
	public long getTotal(PageInfo pi){
		return this.cutTruckerMapper.getTotal(pi);
	}
	
	@Transactional
	public void addCutTrucker(List<CutTrucker> cts){
		if(cts.size()>0){
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("over", "3");//物件3状态表示已经接车
			for (CutTrucker cutTrucker : cts) {
				param.put("object_id",cutTrucker.getObject_id());
				cutTruckerMapper.addCutTrucker(cutTrucker);
				this.productMapper.deletelogobj(param);
				this.productMapper.updateObject_det_over(param);//更新物件状态为3(已经接车)
			}
			param.remove("object_id");
			param.put("logistics_id", cts.get(0).getLogistics_id());
			if(this.cutTruckerMapper.gettotalBylogistics_id(param)==0l){
				this.productMapper.deletelogistics(param);//如果logistics_object没有数据则删除单号
			}
		}
	}
	
	@Transactional
	public void addCutTruckerbyLogistics_id(CutTrucker ct ){
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("logistics_id",ct.getLogistics_id());
		List<String> object_ids = this.productMapper.getObject_idByLogistics_id(param);
		if(object_ids.size()==0){
			this.productMapper.deletelogistics(param);//如果logistics_object没有数据则删除单号
			return;
		}
		List<CutTrucker> cutTruckers = new ArrayList<CutTrucker>();
		CutTrucker cutt = null;
		String date = Util.getUserDate("yyyy-MM-dd HH:mm:ss") ;
		for (String object_id : object_ids) {
			cutt = new CutTrucker();
			cutt.setId(Util.getUUID());
			cutt.setObject_id(object_id);
			cutt.setCuttrucker_location(ct.getCuttrucker_location());
			cutt.setCuttrucker_staff(ct.getCuttrucker_staff());
			cutt.setCuttrucker_time(date);
			cutt.setLogistics_id(ct.getLogistics_id());
			cutTruckers.add(cutt);
		}
		this.addCutTrucker(cutTruckers);//接车
	}
	
	public List<CutTrucker> getAllCuttrucker(PageInfo pi){
		return this.cutTruckerMapper.getAllCuttrucker(pi);
	}
	
}
